package com.atguigu.yygh.utils;


import io.jsonwebtoken.*;
import io.jsonwebtoken.impl.compression.CompressionCodecs;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2025/3/19 23:08
 */
public class JwtHelper {
    private static long tokenExpireTime = 1000 * 60 * 60 * 24 ; // token过期时间，默认1天
    private static String tokenSingKey = "123456"; // 密钥
    // 生成token
    public static String createToken(Long userId, String username) {
        String token = Jwts.builder()
                .setSubject("YYGH-USER") //标识用户身份
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpireTime)) //设置过期时间
                .claim("userId", userId) //设置用户id
                .claim("username", username) //设置用户名
                .signWith(SignatureAlgorithm.HS512, tokenSingKey) //设置签名算法和密钥
                .compressWith(CompressionCodecs.GZIP)  //设置压缩方式
                .compact();//生成token
        return token;
    }
    // 解析token得到userId
    public static Long getUserId(String token) {
        if (StringUtils.isEmpty(token)) return null;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSingKey)
                .parseClaimsJws(token);//解析token
        Integer userId= (Integer) claimsJws.getBody().get("userId");
        return userId.longValue();
    }
    // 解析token得到userName
    public static String getUsername(String token) {
        if (StringUtils.isEmpty(token)) return null;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSingKey).parseClaimsJws(token);
        return (String) claimsJws.getBody().get("username");

    }

    public static void main(String[] args) {
        Long userId = 123456L;
        String username = "admin";
        String token = createToken(userId, username);
        System.out.println(token);
        System.out.println(getUserId("eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWKi5NUrJSiox099ANDXYNUtJRSq0oULIyNDcxMrEwtTQ11FEqLU4t8kwBihkZm5iaQfh5ibmpQH2JKbmZeUq1AC2SvIdHAAAA.Vus8HoQaIZ7PZ2FisdBBzK0qt5y67Bw--fts_8WJFch0jZsY2mnVCQkd3PCHmhWMZICTNhvBgI52goo8VqTGvA"
        ));
    }
}
